package com.scalar.chiptrack.finance.proformainvoice.actioncommands;

import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.finance.proformainvoice.forms.ProformaInvoiceForm;
import com.scalar.chiptrack.finance.proformainvoice.dao.ProformaInvoiceDAO;
import com.scalar.chiptrack.finance.proformainvoice.ProformaInvoiceHelper;
import com.scalar.chiptrack.operations.release.ReleaseHelper;
import com.scalar.chiptrack.operations.process.dao.NewProductDAO;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Calendar;

/**
 * User: KP
 * Date: Sep 28, 2006
 * Time: 3:10:16 PM
 */
public class ProformaInvoiceSaveCommand extends ActionCommand
{
    private static final String ACTION_NAME = "/newproformaInvoice.do";

    public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) { }

        String action       = request.getParameter( "action" );         //THIS IS ONLY USED TO CALL RESPECTIVE ACTION CLASS
        String forward      = "view";
        HashMap errors      = ( HashMap ) request.getAttribute( ERROR_MESSAGES );
        HashMap info        = ( HashMap ) request.getAttribute( INFO_MESSAGES );

        HttpSession mSession    = request.getSession();
        User user               = ( User ) mSession.getAttribute ( SessionKeys.USER_KEY );

        ProformaInvoiceForm invoiceForm     = ( ProformaInvoiceForm ) form;
        DBTransaction dbTransaction         = null;
        boolean success                     = false;
        boolean invoiceSavedSuccessfully    = false;

        if ( user == null )
        {
            mSession.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME);
            return ( mapping.findForward ( "login" ) );
        }
        else
        {
            if ( user.isActionAllowed ( Functionality.PRO_FORMA_INVOICE , User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }

        try
        {
            if( ACTION_SAVE.equalsIgnoreCase( action ) ) // This Block of code used to show print view screen after pressing save button in proforma invoice and also used to save new release information into DB after pressing approval button
            {
                String isConfirm = request.getParameter( "isConfirm" ); //this is used to approve the releases...here approving is directly done while saving new releases.

                if( "true".equalsIgnoreCase( isConfirm ) )
                {
                    //Now we are saving directly without asking confirmation screen
                }
                else
                {
                    if ( !isTokenValid ( request ) )
                    {
                        errors.put ( "Proforma Invoice Already Saved", null );
                        invoiceSavedSuccessfully = true; /* Infact release already saved successfully*/
                        saveToken ( request );
                        forward = "search_invoices";
                    }
                    else
                    {
                        if( ( ProformaInvoiceDAO.isInvoiceNumberExists( null, invoiceForm.getInvoiceNo() ) ) && ( invoiceForm.getInvoiceId() == -1 ) )
                        {
                            saveToken ( request );
                            errors.put ( "Could not Save the Proforma Invoice since Proforma Invoice # already exists", null );
                            forward = "new";
                            request.setAttribute( "actionType", "new" );
                        }
                        else
                        {
                            resetToken ( request );
                            //forward = "search_invoices";
                            try
                            {
                                dbTransaction = DBTransaction.getInstance();
                                dbTransaction.begin();



                                if( invoiceForm.getInvoiceId() == -1 )
                                {
                                    if ( invoiceForm.getBankId() == -1)
                                    {
                                        int finalbankId = -1;
                                        finalbankId = UserDAO.saveClientBankAddressDetails(dbTransaction, invoiceForm.getBankName(), invoiceForm.getBankAddress1(), invoiceForm.getBankCity(), invoiceForm.getBankState(), invoiceForm.getBankZipCode(), invoiceForm.getBankCountry(),  invoiceForm.getAba(), invoiceForm.getAcct(), invoiceForm.getSwiftcode(), invoiceForm.getBankId());
                                        if (finalbankId != -1)
                                        invoiceForm.setBankId(finalbankId);
                                    }
                                    ProformaInvoiceDAO.saveProformaInvoiceInfo( dbTransaction, invoiceForm, user );
                                    ProformaInvoiceDAO.saveProformaInvoiceLineItemDetails( dbTransaction, invoiceForm );
                                }
                                success = true;
                            }
                            catch( Exception e )
                            {
                                forward = "search_invoices";
                                e.printStackTrace();
                                throw new ScalarException( "Could not Save the Proforma Invoice to database." );
                            }
                            finally
                            {
                                if( dbTransaction != null )
                                {
                                    if( success == true )
                                    {
                                        try{
                                            dbTransaction.commit();
                                            info.put( "Proforma Invoice has been saved successfully"  , null );
                                            //info.put ( "Proforma Information Saved Successfully", null );
                                            //String approveLink= "/"+ ConfigManager.getChipTracContext()+"/testRelease.do?action=approve&releaseId=" + releaseForm.getReleaseId();
                                            //info.put ( "Click here to <a href='" + approveLink + "' onmouseover=\"window.status='Click here to Approve Test Release';return true\" onmouseout=\"window.status='';return true\"> Approve </a> Test Release", null );
                                        }catch( Exception e ){
                                            e.printStackTrace();
                                            errors.put ( "Error while committing the database ", null );
                                        }
                                    }
                                    else
                                    {
                                        try{
                                            dbTransaction.rollback();
                                            errors.put ( "Proforma Information saving aborted", null );
                                        }catch( Exception e ){
                                            e.printStackTrace();
                                            errors.put ( "Error occurred while rolling back", null );
                                        }
                                    }
                                }
                            }

                            saveToken( request );

                            forward = "view";

                            /*if( releaseForm.isReleaseModified() )
                            {
                                forward = "view";
                                request.setAttribute( "isApprove", "true" );// Used to show Confirm Button in print view screen
                            }
                            else
                            {
                                forward = "search_invoices";
                            }*/
                        }
                    }
                }
            }
            else if( ACTION_UPDATE.equalsIgnoreCase( action ) ) // This Block of code used to show approval(print view) screen after pressing save button in existing release scr and also used to save existing release information into DB after pressing approval button
            {
                String isUpdate     = request.getParameter( "isUpdate" ); //THIS IS USED TO UPDATE THE RELEASES...
                String isCancelled  = request.getParameter( "isCancelled" );

                if( "true".equalsIgnoreCase( isCancelled ) )
                {
                    if ( !isTokenValid ( request ) )
                    {
                        errors.put ( "Proforma Invoice Already Cancelled", null );
                        invoiceSavedSuccessfully = true; /* Infact invoice already saved successfully*/
                        saveToken ( request );
                        forward = "search_invoices";
                    }
                    else
                    {
                        resetToken ( request );
                        try
                        {
                            dbTransaction = DBTransaction.getInstance();
                            dbTransaction.begin();

                            ProformaInvoiceDAO.updateProformaInvoiceStatus( dbTransaction, invoiceForm.getInvoiceId(), Constants.RELEASE_STATUS_CANCELLED , user.getUserName() );

                            success = true;
                            invoiceSavedSuccessfully = true;
                        }
                        catch( Exception e )
                        {
                            forward = "search_invoices";
                            e.printStackTrace();
                            throw new ScalarException( "Could not Update Status for the Proforma Invoice." );
                        }
                        finally
                        {
                            if( dbTransaction != null )
                            {
                                if( success == true )
                                {
                                    try{
                                        dbTransaction.commit();
                                        info.put( "Proforma Invoice # " + invoiceForm.getInvoiceNo() + " has been cancelled"  , null );
                                    }catch( Exception e ){
                                        e.printStackTrace();
                                        errors.put ( "Error while committing the database ", null );
                                    }
                                }
                                else
                                {
                                    try{
                                        dbTransaction.rollback();
                                        errors.put ( "Proforma Information saving aborted", null );
                                    }catch( Exception e ){
                                        e.printStackTrace();
                                        errors.put ( "Error occurred while rolling back", null );
                                    }
                                }
                            }
                        }

                        saveToken( request );

                        forward = "search_invoices";
                    }
                }
                else if( "true".equalsIgnoreCase( isUpdate ) )
                {
                    //Now we are saving directly without asking confirmation screen
                }
                else
                {
                    if ( !isTokenValid ( request ) )
                    {
                        errors.put ( "Proforma Invoice already updated", null );
                        invoiceSavedSuccessfully = true; /* Infact release already updated successfully*/
                        saveToken ( request );
                    }
                    else
                    {
                        resetToken ( request );
                        if( invoiceForm.getInvoiceId() > 0 )
                        {
                            try
                            {
                                dbTransaction = DBTransaction.getInstance();
                                dbTransaction.begin();
                                if ( invoiceForm.getBankId() == -1)
                                {
                                    int finalbankId = -1;
                                    finalbankId = UserDAO.saveClientBankAddressDetails(dbTransaction, invoiceForm.getBankName(), invoiceForm.getBankAddress1(), invoiceForm.getBankCity(), invoiceForm.getBankState(), invoiceForm.getBankZipCode(), invoiceForm.getBankCountry(),  invoiceForm.getAba(), invoiceForm.getAcct(), invoiceForm.getSwiftcode(), invoiceForm.getBankId());
                                    if (finalbankId != -1)
                                    invoiceForm.setBankId(finalbankId);
                                }
                                ProformaInvoiceDAO.saveProformaInvoiceInfo( dbTransaction, invoiceForm, user );
                                ProformaInvoiceDAO.saveProformaInvoiceLineItemDetails( dbTransaction, invoiceForm );

                                success = true;
                            }
                            catch( Exception e )
                            {
                                forward = "search_invoices";
                                e.printStackTrace();
                                throw new ScalarException( "Could not Save the Proforma Invoice to database." );
                            }
                            finally
                            {
                                if( dbTransaction != null ){
                                    if( success == true ){
                                        try{
                                            dbTransaction.commit();
                                            info.put ( "Proforma Invoice Information Saved Successfully ", null );
                                        }catch( Exception e ){
                                            e.printStackTrace();
                                            errors.put ( "Error while committing the database ", null );
                                        }
                                    }
                                    else
                                    {
                                        try{
                                            dbTransaction.rollback();
                                            errors.put ( "Proforma Invoice Information saving aborted", null );
                                        }catch( Exception e ){
                                            e.printStackTrace();
                                            errors.put ( "Error occurred while rolling back", null );
                                        }
                                    }
                                }
                            }
                        }

                        saveToken( request );

                        forward = "view";

                        /*if( releaseForm.isReleaseModified() )
                        {
                            forward = "view";
                            request.setAttribute( "isApprove", "true" );// Used to show Confirm Button in print view screen
                        }
                        else
                        {
                            forward = "search_invoices";
                        }*/
                    }
                }
            }
        }
        catch( Exception e )
        {
            forward = "search_invoices";
            e.printStackTrace();
            //throw new ScalarException( "Could not Save the Proforma Invoice to database." );
            errors.put ("Could not Save the Proforma Invoice to database.", null );
        }
        finally
        {
            if( invoiceSavedSuccessfully || forward.equalsIgnoreCase( "search_invoices" ) )  // This block variable used to existing invoice search screen.
            {
                ProformaInvoiceHelper.resetProformaInvoiceForm( invoiceForm );

                Calendar calendar = Calendar.getInstance();
                invoiceForm.setSearchYear( ( calendar.get( Calendar.YEAR ) ) + "" );

                request.setAttribute( "yearList", ReleaseHelper.getYearList() );
                request.setAttribute( "partNumberList", NewProductDAO.loadPartNumbers (null, 1, Constants.LOCATION_TYPE_FG, true, true, true, 0 ) );
                request.setAttribute( "salesOrderList", ProformaInvoiceDAO.loadApprovedSalesOrderList( null ) );
                request.setAttribute( "customerList", CustomerDAO.getAllCustomerNamesByUserType( null, user ) );
            }
        }
        return mapping.findForward( forward );
    }

}
